package zero.tech.games.dn.work.sync;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

import zero.tech.core.ZeroContext;
import zero.tech.core.data.Resp;
import zero.tech.core.work.AynWork;
import zero.tech.games.common.Code;
import zero.tech.games.common.UserLastRoomUtil;
import zero.tech.games.common.WaterMode;
import zero.tech.games.dn.data.DnConfig;
import zero.tech.games.dn.data.DnRoomCache;
import zero.tech.games.entity.games.Club;
import zero.tech.games.logic.common.Room;
import zero.tech.games.logic.data.consts.LOGICCMD;
import zero.tech.games.logic.service.api.ILogicService;
import zero.tech.wsnet.controller.LogicController;
import zero.tech.wsnet.data.Message;

public class PlayerTaotaiLeaveCalculateSyncWork extends AynWork{
	private Room room;
	private LogicController logicController;
	@Override
	public void init(Object... objs) throws Exception {
		this.room=(Room) objs[0];
		this.logicController=(LogicController) objs[1];
	}

	@Override
	public void run() {
		//结算代码在这里
		synchronized (room.getTransform_lock()) {
			Club club=room.getClub();
			if(club!=null) {
				//结算代码在此处
				playerTransform(room,logicController);
			}
		}
	}

	private void playerTransform(Room room, LogicController logicController) {
		DnRoomCache dnRoomCache = (DnRoomCache) room.getRoomCache();
		int uid=logicController.getId();
		if(!dnRoomCache.getAdvances().contains(uid)) {
			//还未结算过,需要被结算
			List<Integer> uids=new ArrayList<>();
			uids.add(uid);
			String joiners=JSONObject.toJSONString(uids);
			DnConfig dnConfig = (DnConfig) room.getGameConfig();
			int water_mode=dnConfig.getWater_mode();
			long water_num=dnConfig.getWater_num();
			Map<Integer,Long> goldchangemap=new HashMap<>();
			Map<Integer,Long> watermap=new HashMap<>();
			if(water_mode==WaterMode.AA) {
				//AA抽水
				watermap.put(uid, water_num);
			}
			long gold_from_gate=logicController.getGold_from_gate();
			long gold=logicController.getGold();
			if(watermap.containsKey(uid)) {
				gold=gold-watermap.get(uid);
			}
			logicController.setGold(gold);
			long change=gold-gold_from_gate;
			goldchangemap.put(uid, change);
			ILogicService logicService=ZeroContext.getInstance(ILogicService.class);
			logicService.gameUpdateBatch(room, joiners, null, goldchangemap, watermap);
			dnRoomCache.getAdvances().add(uid);//加入提前结算列表
		}
		//移除最后房间信息
		UserLastRoomUtil userLastRoomUtil = ZeroContext.getInstance(UserLastRoomUtil.class);
		userLastRoomUtil.delete(String.valueOf(uid), room.getRoom_id());
		logicController.getWebClient().sendMessage(Message.build(LOGICCMD.RES_LEAVE, Resp.build(Code.OK, "离开成功")));
	}

}
